'use strict'

###*
 # @ngdoc directive
 # @name xoceanApp.directive:ensureUnique
 # @description
 # # ensureUnique
 # Used in #/wizard/step_2. Ensure modelid to be unique.
###
angular.module('xoceanApp')
  .directive('ensureUnique', (Subject)->
    restrict: 'A'
    require: 'ngModel'
    link: (scope, element, attrs, ctrl) ->
      ctrl.$setValidity('unique', true)
      element.on 'focus', ->
        ctrl.$setValidity('unique', true)
        return

      element.on 'blur', ->
        return if not ctrl.$viewValue
        value = ctrl.$viewValue
        if not /_vs/.test(value)
          value += '_vs'
          scope.$parent.basicInfo.modelid = value
        Subject.checkId(value).then (data)->
          if data.result is 0
            ctrl.$setValidity('unique', true)
          else
            ctrl.$setValidity('unique', false)
          return
        , (data)->
          ctrl.$setValidity('unique', false)
          return
  )
